package com.dove.authority.service.impl;

import com.dove.authority.Async.AuthorityAsync;
import com.dove.authority.entity.Enterprise;
import com.dove.authority.entity.Role;
import com.dove.authority.entity.vo.EnterpriseVo;
import com.dove.authority.mapper.EnterpriseMapper;
import com.dove.authority.mapper.PermissionMapper;
import com.dove.authority.mapper.RoleMapper;
import com.dove.authority.service.EnterpriseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dove.entity.GlobalException;
import com.dove.entity.Result;
import com.dove.entity.UserDetailsImpl;
import com.dove.util.SecurityContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author run
 * @since 2021-03-21
 */
@Service
public class EnterpriseServiceImpl extends ServiceImpl<EnterpriseMapper, Enterprise> implements EnterpriseService {

    @Autowired
    private EnterpriseMapper enterpriseMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private AuthorityAsync authorityAsync;

    @Override
    public EnterpriseVo getEnterpriseInfo() {
        UserDetailsImpl userDetails = SecurityContextUtil.getUserDetails();
        return enterpriseMapper.getEnterpriseInfo(userDetails.getEnterpriseId());
    }

    @Override
    public boolean updateEnterprise(Enterprise enterprise) {
        UserDetailsImpl userDetails = SecurityContextUtil.getUserDetails();
        enterprise.setId(userDetails.getId());
        return enterpriseMapper.updateById(enterprise) > 0;
    }

    @Override
    @Transactional
    public boolean createEnterprise(Enterprise enterprise) {
        UserDetailsImpl userDetails = SecurityContextUtil.getUserDetails();
        if (userDetails.getEnterpriseId() != null){
            throw new GlobalException(Result.error("已加入企业，无法创建"));
        }

        boolean isSuccess = enterpriseMapper.insert(enterprise) > 0;

        if (!isSuccess){
            throw new GlobalException(Result.error("创建失败"));
        }

        //创建初始角色
        Role role = new Role();
        role.setEnterpriseId(enterprise.getId());
        role.setName("创始人");
        isSuccess = roleMapper.insert(role) > 0;

        if (!isSuccess){
            throw new GlobalException(Result.error("创建失败"));
        }

        //赋予初始角色所有权限
        List<Long> allPermission = permissionMapper.getAllPermission();
        Future<String> task = authorityAsync.addPermissionOfRole(allPermission, role.getId());

        while (!task.isDone()){
            Thread.yield();
        }

        return true;
    }
}
